package org.example.aienglishapp.controller.speech.chapter;

import org.example.aienglishapp.dto.speech.chapter.ChapterDTO;
import org.example.aienglishapp.entity.speech.chapter.Chapter;
import org.example.aienglishapp.mapper.speech.chapter.ChapterMapper;
import org.example.aienglishapp.util.response.ResponseResult;
import org.example.aienglishapp.util.response.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/chapters")
public class ChapterController {

    @Autowired
    private ChapterMapper chapterMapper;

    @Autowired
    @Qualifier("speechRedisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    private static final String CACHE_KEY_PREFIX = "chapter:";

    @GetMapping("/{id}")
    public ResponseResult<ChapterDTO> getChapterById(@PathVariable Long id) {
        // 尝试从 Redis 中获取章节信息
        String key = CACHE_KEY_PREFIX + id;
        Chapter chapter = (Chapter) redisTemplate.opsForValue().get(key);

        if (chapter == null) {
            // 如果 Redis 中没有，从数据库中获取
            chapter = chapterMapper.findById(id);
            if (chapter != null) {
                // 将章节信息存储到 Redis
                redisTemplate.opsForValue().set(key, chapter);
            } else {
                return ResponseResult.failed(ResultCode.NOT_FOUND.getCode(), "章节不存在");
            }
        }
        // 转换为 DTO
        ChapterDTO chapterDTO = new ChapterDTO(chapter.getChapterId(), chapter.getBookId(), chapter.getEtitle(), chapter.getTitle());
        return ResponseResult.success(chapterDTO);
    }

    @GetMapping
    public ResponseResult<List<ChapterDTO>> getAllChapters() {
        List<Chapter> chapters = chapterMapper.findAll();
        // 转换为 DTO 列表
        List<ChapterDTO> chapterDTOs = chapters.stream()
                .map(c -> new ChapterDTO(
                        c.getChapterId(),  // 确保这里调用了正确的 getter 方法
                        c.getBookId(),
                        c.getEtitle(),
                        c.getTitle()))
                .collect(Collectors.toList());
        return ResponseResult.success(chapterDTOs);
    }

    @GetMapping("/byBookId")
    public ResponseResult<List<ChapterDTO>> getChaptersByBookId(@RequestParam Long bookId) {
        // 尝试从 Redis 中获取章节信息
        String key = CACHE_KEY_PREFIX + "book:" + bookId;
        List<Chapter> chapters = (List<Chapter>) redisTemplate.opsForValue().get(key);

        if (chapters == null) {
            // 如果 Redis 中没有，从数据库中获取
            chapters = chapterMapper.findByBookId(bookId);
            if (chapters != null && !chapters.isEmpty()) {
                // 将章节信息存储到 Redis
                redisTemplate.opsForValue().set(key, chapters);
            } else {
                return ResponseResult.failed(ResultCode.NOT_FOUND.getCode(), "该书籍没有章节");
            }
        }

        // 转换为 DTO 列表
        List<ChapterDTO> chapterDTOs = chapters.stream()
                .map(c -> new ChapterDTO(
                        c.getChapterId(),
                        c.getBookId(),
                        c.getEtitle(),
                        c.getTitle()))
                .collect(Collectors.toList());

        return ResponseResult.success(chapterDTOs);
    }

    @PostMapping
    public ResponseResult<Integer> createChapter(@RequestBody Chapter chapter) {
        int result = chapterMapper.insert(chapter);
        if (result > 0) {
            // 将章节信息存储到 Redis
            String key = CACHE_KEY_PREFIX + chapter.getChapterId();
            redisTemplate.opsForValue().set(key, chapter);
            return ResponseResult.success(result);
        } else {
            return ResponseResult.failed(ResultCode.INTERNAL_ERROR.getCode(), "创建章节失败");
        }
    }

    @PutMapping
    public ResponseResult<Integer> updateChapter(@RequestBody Chapter chapter) {
        int result = chapterMapper.update(chapter);
        if (result > 0) {
            // 更新 Redis 中的章节信息
            String key = CACHE_KEY_PREFIX + chapter.getChapterId();
            redisTemplate.opsForValue().set(key, chapter);
            return ResponseResult.success(result);
        } else {
            return ResponseResult.failed(ResultCode.INTERNAL_ERROR.getCode(), "更新章节失败");
        }
    }

    @DeleteMapping("/{id}")
    public ResponseResult<Integer> deleteChapter(@PathVariable Long id) {
        int result = chapterMapper.deleteById(id);
        if (result > 0) {
            // 删除 Redis 中的章节信息
            String key = CACHE_KEY_PREFIX + id;
            redisTemplate.delete(key);
            return ResponseResult.success(result);
        } else {
            return ResponseResult.failed(ResultCode.NOT_FOUND.getCode(), "删除章节失败");
        }
    }
}
